package com.example.distributedlock.controller;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * RedissonController
 *
 * @author lx
 * @date 2024-03-21 15:04
 */
@RestController
public class RedissonController {
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;


    @GetMapping("/r")
    public String a() {
        redisTemplate.opsForValue().set("lx", 1);
        return "ok";
    }

    @GetMapping("/redisson")
    public String redisson() throws InterruptedException {
//        锁的名字相同即为同一把锁
        RLock lock = redissonClient.getLock("同一把锁");
        lock.lock();
        try {
            Object lx = redisTemplate.opsForValue().get("lx");
            Thread.sleep(2000);
            if (lx != null) {
                int i = (int) lx - 1;
                redisTemplate.opsForValue().set("lx", i);
                System.out.println(i);
                return String.valueOf(i);
            }
            return String.valueOf(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            return String.valueOf(-1000);
        } finally {
            lock.unlock();
        }
    }
}
